<template>
  <div :class="{'avue--collapse':isCollapse}"
       class="avue-contail">
    <div class="avue-header">
      <!-- 顶部导航栏 -->
      <top ref="childHomeTop" />
    </div>

    <div class="avue-layout">
      <logo />
      <div class="avue-left"
           >
        <!-- 左侧导航栏 -->
        <sidebar />
      </div>
      <div class="avue-main"
           >
        <!-- 顶部标签卡 -->
        <tags />
        <!-- 主体视图层 -->
        <el-scrollbar class="main">
          <router-view ref="child"
                       :class="['avue-view',showExamine === tag.value?'showExamine':'']"
                       :key="key"
                       id="sone-container-warp"
                       v-if="checkDev" />
          <template v-else>
            <keep-alive>
              <router-view ref="child"
                           :class="['avue-view',showExamine === tag.value?'showExamine':'']"
                           :key="key"
                           id="sone-container-warp"
                           v-if="$route.meta.$keepAlive" />
            </keep-alive>
            <router-view ref="child"
                         :class="['avue-view',showExamine === tag.value?'showExamine':'']"
                         :key="key"
                         id="sone-container-warp"
                         v-if="!$route.meta.$keepAlive" />
          </template>
        </el-scrollbar>
        <!-- 版本号 -->
        <div class="footer"
             ></div>
      </div>
    </div>
    <div class="avue-shade"
         @click="showCollapse" />
  </div>
</template>

<script>
import { mapGetters } from 'vuex'
import tags from './tags'
import top from './top/'
import sidebar from './sidebar/'
import admin from '../../util/admin'
import { getStore } from '../../util/store'
import * as SockJS from 'sockjs-client'
import Stomp from 'stomp-websocket'
import store from '../../store'
import logo from './logo'

export default {
  name: 'Index',
  components: {
    logo,
    top,
    tags,
    sidebar
  },
  data () {
    return {
      // 刷新token锁
      refreshLock: false,
      // 刷新token的时间
      refreshTime: '',
      // 计时器
      timer: '',
    }
  },
  created () {
    // 实时检测刷新token
    this.refreshToken()
  },
  destroyed () {
    clearInterval(this.refreshTime)
    clearInterval(this.timer)
    this.disconnect()
  },
  mounted () {
    this.init()
    this.initWebSocket()
  },
  computed: {
    ...mapGetters(['userInfo', 'isLock', 'isCollapse', 'website', 'expires_in', 'language', 'showExamine', 'tag','currentModule']),
    key () {
      return this.$route.fullPath
    },
    checkDev () {
      return process.env.NODE_ENV === 'development'
    }
  },
  watch: {
    language () {
      for (const k in this.$refs.child) {
        if (k.indexOf('option') !== -1) this.$set(this.$refs.child, k, this.$refs.child[k])
      }
    }
  },
  methods: {
    showCollapse () {
      this.$store.commit('SET_COLLAPSE')
    },
    // 屏幕检测
    init () {
      this.$store.commit('SET_SCREEN', admin.getScreen())
      window.onresize = () => {
        setTimeout(() => {
          this.$store.commit('SET_SCREEN', admin.getScreen())
        }, 0)
      }
    },
    // 实时检测刷新token
    refreshToken () {
      this.refreshTime = setInterval(() => {
        const token = getStore({
          name: 'access_token',
          debug: true
        })

        if (this.validatenull(token)) {
          return
        }

        if (this.expires_in <= 1000 && !this.refreshLock) {
          this.refreshLock = true
          this.$store
            .dispatch('RefreshToken')
            .catch(() => {
              clearInterval(this.refreshTime)
            })
          this.refreshLock = false
        }
        this.$store.commit('SET_EXPIRES_IN', this.expires_in - 10)
      }, 10000)
    },
    initWebSocket () {
      this.connection()
      const self = this
      // 断开重连机制,尝试发送消息,捕获异常发生时重连
      this.timer = setInterval(() => {
        try {
          self.stompClient.send('test')
        } catch (err) {
          console.log('断线了: ' + err)
          self.connection()
        }
      }, 5000)
    },
    connection () {
      const token = store.getters.access_token
      const logUser = this.userInfo
      const authorization = 'Bearer ' + token
      const headers = {
        'Authorization': authorization
      }
      // 建立连接对象， 连接服务端提供的通信接口，连接以后才可以订阅广播消息和个人消息
      this.socket = new SockJS(this.currentModule.routePrefix+'/websocket/register')
      // 获取STOMP子协议的客户端对象
      this.stompClient = Stomp.over(this.socket)
      this.stompClient.debug = null
      // 向服务器发起websocket连接
      this.stompClient.connect(headers, () => {
        // 订阅服务端提供的点对点消息
        const des = '/user/' + logUser.userId + '/message/pointToPoint'
        this.stompClient.subscribe(des, (result) => {
          this.$refs.childHomeTop.getNoticeToDoList()
          this.$notify({
            title: '新消息',
            type: 'warning',
            dangerouslyUseHTMLString: true,
            message: '您有新的待办消息', // result.body
            offset: 60
          })
        })
      }, (err) => {

      })
    },
    disconnect () {
      if (this.stompClient != null) {
        this.stompClient.disconnect()
        console.log('Disconnected')
      }
    },
  }
}
</script>
<style lang="scss">
.avue-view {
  transition: all 0.2s;
}
.showExamine {
  width: calc(100% - 300px) !important;
}
.avue-main .basic-container > .el-card {
  border-top-left-radius: 0;
  border-top-right-radius: 0;
  box-shadow: none;
  border: 1px solid #f1f5f8 !important;
}
.footer {
  width:calc(100% - 260px);
  height: 30px;
  position: fixed;
  bottom: 0;
  padding: 0 10px;
  background: #ebebeb;
  border-top: 1px solid #e4e4e4;
  display: flex;
  flex-flow: row nowrap;
  align-items: center;
  justify-content: space-between;
  color: #bec1c6;
  font-size: 12px;
  &::before {
    content: "Version 3.0";
  }
  &:after {
    content: "© SipingSoft";
  }
}
</style>
